package models

import (
	"fmt"
	"log"
	"toy-car/pkg/setting"

	"gorm.io/driver/mysql"

	"gorm.io/gorm"
)

var db *gorm.DB

type ModelBase struct {
	ID         int `gorm:"primary_key" json:"id"`
	CreatedOn  int `json:"createTime"`
	ModifiedOn int `json:"modifiedTime"`
}

func init() {
	var (
		err                          error
		dbName, user, password, host string
	)

	sec, err := setting.Cfg.GetSection("database")
	if err != nil {
		log.Fatal(2, "fail to get section 'database': %v", err)
	}

	// dbType = sec.Key("TYPE").String()
	dbName = sec.Key("NAME").String()
	user = sec.Key("USER").String()
	password = sec.Key("PASSWORD").String()
	host = sec.Key("HOST").String()
	// tablePrefix = sec.Key("TABLE_PREFIX").String()

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, dbName)
	mysqlConfig := mysql.Config{
		DSN:                       dsn,   // DSN data source name
		DefaultStringSize:         191,   // string 类型字段的默认长度
		DisableDatetimePrecision:  true,  // 禁用 datetime 精度，MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex:    true,  // 重命名索引时采用删除并新建的方式，MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn:   true,  // 用 `change` 重命名列，MySQL 8 之前的数据库和 MariaDB 不支持重命名列
		SkipInitializeWithVersion: false, // 根据版本自动配置
	}
	db, err = gorm.Open(mysql.New(mysqlConfig))

	if err != nil {
		log.Println(err)
	} else {
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(10)
		sqlDB.SetMaxOpenConns(100)
	}

	log.Println("db -> ")
	log.Println(db)
	var t string
	db.Raw("select NOW()").Scan(&t)
	log.Println(t)

	err = db.AutoMigrate(

		SysBaseMenuParameters{},
		SysRoleMenu{},
		SysRole{},
		SysUserRole{},
		SysUserNew{},
		SysPerm{},
		SysMenuNew{},
		SysDept{},
		SysPermModule{},
		SysApi{},

		SysBaseMenu{},
		SysBaseMenuBtn{},
		SysUser{},
		SysAuthority{},
		SysUserAuthority{},

		SysMenu{},
		JwtBlacklist{},
		SysDictionary{},
		SysDictionaryDetail{},

		SysAutoCode{},
	)
}
